<!-- pages/editProfile/editProfile.vue -->
<template>
	<view class="page-container">
		<!-- Custom Navigation Bar -->
		<view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="nav-content">
				<text class="nav-back" @click="handleBack">
					<u-icon name="arrow-left" size="16" color="#303133"></u-icon>
				</text>
				<text class="nav-title">编辑简介</text>
				<text class="nav-confirm" @click="confirmProfileChanges">确认</text>
			</view>
		</view>

		<!-- Main Content Area -->
		<view class="main-content" :style="{ paddingTop: (statusBarHeight + 44) + 'px' }">
			<view class="editor-wrapper">
				<textarea
					class="bio-textarea"
					v-model="currentBio"
					:maxlength="maxBioLength"
					placeholder="分享日常小快乐~"
					:show-confirm-bar="false"
					:adjust-position="false"
					auto-height
					focus
				/>
				<view class="char-counter">
					{{ bioLength }}/{{ maxBioLength }}
				</view>
			</view>

			<view class="info-text">
				7天内可修改 3 次简介，05.16 前还可修改 3 次。
			</view>
		</view>
	</view>
</template>

<script>
// 导入更新用户信息的API
import { getUserInfoUpdate } from '@/request/api.js';
export default {
	data() {
		return {
			statusBarHeight: 0, // For custom navigation bar
			currentBio: '',
			initialBio: '', // To check for changes
			maxBioLength: 100,
		};
	},
	computed: {
		bioLength() {
			return this.currentBio.length;
		}
	},
	onLoad(options) {
		// Get status bar height for custom navigation bar
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight || 0;

		// Get currentBio passed from the previous page
		if (options && options.currentBio) {
			this.currentBio = decodeURIComponent(options.currentBio);
			this.initialBio = this.currentBio; // Store initial value
		} else {
            // Set default if not passed, based on your image
            this.currentBio = '分享日常小快乐~ \n吃🥢\n喝🥂\n玩💃\n看🎬';
            this.initialBio = this.currentBio;
        }
	},
	methods: {
		handleBack() {
			if (this.currentBio !== this.initialBio) {
				uni.showModal({
					title: '提示',
					content: '简介已修改，是否保存？',
					cancelText: '不保存',
					confirmText: '保存',
					success: (res) => {
						if (res.confirm) {
							this.confirmProfileChanges();
						} else if (res.cancel) {
							uni.navigateBack();
						}
					}
				});
			} else {
				uni.navigateBack();
			}
		},
		confirmProfileChanges() {
			// 如果简介没有变化，直接返回
			if (this.currentBio === this.initialBio) {
				uni.navigateBack();
				return;
			}
			
			uni.showLoading({ title: '正在保存...' });

			// 准备API请求参数，只包含变更的字段和用户ID
			const params = {
				userId: this.$store.state.userInfo.userId, // 从Vuex获取当前用户ID
				des: this.currentBio // 要更新的简介内容
			};
			
			// 调用更新接口
			getUserInfoUpdate(params).then(res => {
				uni.hideLoading();
				// 检查后端返回的 code，200或0通常表示成功
				if (res.data && (res.data.code === 200 || res.data.code === 0)) {
					// 触发全局事件，通知上一个页面（edit.vue）更新简介
					// 这是实现“回显”的关键
					uni.$emit('profileBioUpdated', this.currentBio);
					
					uni.showToast({
						title: '简介已更新',
						icon: 'success',
						duration: 1500
					});

					// 延迟返回，让用户看到提示
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					// 显示后端返回的错误信息
					uni.showToast({
						title: res.data.msg || '保存失败，请稍后再试',
						icon: 'none'
					});
				}
			}).catch(err => {
				uni.hideLoading();
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
				console.error("更新简介失败:", err);
			});
		}
	},
	// Handle native back button press (Android physical back button)
	onBackPress(options) {
		if (options.from === 'backbutton' && this.currentBio !== this.initialBio) {
			this.handleBack(); // Use the same logic as custom back button
			return true; // Prevent default back navigation
		}
		// If no changes or not from backbutton, allow default behavior
		return false;
	}
};
</script>

<style lang="scss">
	// #ifdef APP-PLUS
	page {
		padding-top: 90rpx!important;
	}
	// #endif
.page-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f8f8f8; /* A common light grey background */
}

/* Custom Navigation Bar */
.custom-nav-bar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	background-color: #ffffff;
	z-index: 99;
	border-bottom: 1px solid #eee;
}

.nav-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 44px; /* Standard nav bar height */
	padding: 0 15px;
}

.nav-back {
	font-size: 22px; /* Adjust size for visibility */
	font-weight: bold;
	color: #333;
	width: 40px; /* Tappable area */
}

.nav-title {
	font-size: 17px;
	font-weight: 600;
	color: #000;
	text-align: center;
	flex-grow: 1;
}

.nav-confirm {
	font-size: 16px;
	color: #fa5151; /* Pinkish-red, similar to image */
	width: 40px; /* Tappable area */
	text-align: right;
}

/* Main Content Area */
.main-content {
	flex-grow: 1;
	padding: 15px; /* Padding for the content below the nav bar */
	/* paddingTop is dynamically set to account for nav bar height */
}

.editor-wrapper {
	background-color: #ffffff;
	border-radius: 8px;
	padding: 12px;
	margin-bottom: 15px;
}

.bio-textarea {
	width: 100%;
	min-height: 120px; /* Minimum height */
	font-size: 16px;
	line-height: 1.6;
	color: #333;
	padding: 0; /* Textarea often has its own padding, adjust if needed */
    box-sizing: border-box;
}

.char-counter {
	text-align: right;
	font-size: 13px;
	color: #b2b2b2;
	margin-top: 8px;
}

.info-text {
	font-size: 13px;
	color: #999999;
	line-height: 1.5;
}
</style>